<?php
class CF_Session
{
	const ELEMENT_BASE_NAME = '_CF_';
	
	protected static $_elements = array();
	/**
	 * 
	 * @var CF_Session_SaveHander_Interface
	 */
	protected static $_saveHandler;
	
	/**
	 * @var boolean
	 */
	protected static $_started = false;
	
	/**
	 * @return CF_Session
	 */

	public static function start()
	{
		if(!self::$_started){
			session_start();
			self::$_started = true;
			
			if(!isset($_SESSION[self::ELEMENT_BASE_NAME]))
				$_SESSION[self::ELEMENT_BASE_NAME] = array();
		}
	}
	
	public static function setSaveHander(CF_Session_SaveHandler_Interface $saveHandler)
	{
		self::$_saveHandler = $saveHandler;
		
		session_set_save_handler(
			array(&$saveHandler, 'open'),
            array(&$saveHandler, 'close'),
            array(&$saveHandler, 'read'),
            array(&$saveHandler, 'write'),
            array(&$saveHandler, 'destroy'),
            array(&$saveHandler, 'gc')
		);
	}
	
	/**
	 * 
	 * @param string $name
	 * @return CF_Session_Element
	 */
	public static function getElement($name)
	{
		if(isset(self::$_elements[$name])) return self::$_elements[$name];
		
		$el = new CF_Session_Element($name);
		self::$_elements[$name] = $el;
		return $el;
	}
	
	/**
	 * 
	 * @param string $name
	 * @return boolean
	 */
	public static function has($name)
	{
		return isset($_SESSION[$name]);	
	}
	
	/**
	 * 
	 * @param string $name
	 * @param mixed $default [optional]
	 * @return mixed
	 */
	public static function &get($name, $default = null)
	{
		if(!self::has($name)) return $default;
		return $_SESSION[$name];
	}
	
	/**
	 * 
	 * @param string $name
	 * @param mixed $value
	 * @return void
	 */
	public static function set($name, $value)
	{
		$_SESSION[$name] = $value;
	}
	
	/**
	 * 
	 * @param string $name
	 * @return void
	 */
	public static function remove($name)
	{
		unset($_SESSION[$name]);
	}
}